package com.ramos.kuaixiao.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.SaleCustomerStoreDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.ui.CustomerStoreActivity;
import com.ramos.kuaixiao.ui.ShopDetailActivity;
import com.ramos.kuaixiao.utils.StringUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CustomerAdapter extends RecyclerView.Adapter implements Filterable {

    private List<Customer> tasklist;
    private Context context;
    private ArrayList<Customer> mOriginalValues;
    private final Object mLock = new Object();
    private String keyWrold = ""; // 关键字
    UpdateCarListener updateListener;

    public CustomerAdapter(Context context, List<Customer> hotcourse) {
        this.context = context;
        this.tasklist = hotcourse;

    }

    public void refresh(List<Customer> data) {
        tasklist = data;
        sortDistance(tasklist);
        notifyDataSetChanged();
    }

    private void sortDistance(List<Customer> tasklist) {
        List<Customer> tem1 = new ArrayList<>();
        tem1.clear();
        List<Customer> tem2 = new ArrayList<>();
        tem2.clear();
        for (Customer customer : tasklist) {
            if (StringUtil.isEmpty(customer.getDistance())) {
                tem2.add(customer);
            } else {
                tem1.add(customer);
            }
        }
        Comparator<Customer> comparator = new Comparator<Customer>() {
            public int compare(Customer s1, Customer s2) {
                // 先排年龄
                if (Integer.valueOf(s1.getDistance()) != Integer.valueOf(s2.getDistance())) {
                    return Integer.valueOf(s1.getDistance()) - Integer.valueOf(s2.getDistance());
                } else if (!s1.getName().equals(s2.getName())) {
                    // 年龄相同则按姓名排序
                    return s1.getName().compareTo(s2.getName());
                } else {
                    return 1;
                }
            }
        };
        tasklist.clear();
        //这里就会自动根据规则进行排序
        Collections.sort(tem1, comparator);
        for (int i = 0; i < tem1.size(); i++) {
            Customer stu = tem1.get(i);
            //Log.d("Collections", "dis:" + stu.getDistance());
        }
        tasklist.addAll(tem1);
        tasklist.addAll(tem2);
    }


    @SuppressLint("InflateParams")
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.listitem_customer, null);
        ViewHodler vh = new ViewHodler(view);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);
        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ViewHodler viewHolder = (ViewHodler) holder;
        showText(tasklist.get(position).getName(), viewHolder.tvName);
        showText(tasklist.get(position).getAddress(), viewHolder.tvAddress);
        //viewHolder.tvAddress.setText(tasklist.get(position).getAddress());
        String dis = tasklist.get(position).getDistance();
        if (StringUtil.isEmpty(dis)) {
            viewHolder.tvDistance.setVisibility(View.GONE);
        } else {
            viewHolder.tvDistance.setVisibility(View.VISIBLE);
            viewHolder.tvDistance.setText(dis + "km");
        }
        if(!StringUtil.isEmpty(tasklist.get(position).getTelephone()) && !StringUtil.isEmpty(tasklist.get(position).getQid())){
            viewHolder.icon.setVisibility(View.VISIBLE);
        } else {
            viewHolder.icon.setVisibility(View.GONE);
        }

        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Customer customer = tasklist.get(position);
                SaleCustomerStoreDB db = new SaleCustomerStoreDB();
                //CustomerStoreDB db = new CustomerStoreDB();
                //此处需使用QID查询门店
                if (db.hasData()) {
                    if(db.findAllCustomerStore(customer.getId()).size() == 0){
                        Intent intent = new Intent(context, ShopDetailActivity.class);
                        intent.putExtra("customer", customer);
                        context.startActivity(intent);
                    } else {
                        Intent intent = new Intent(context, CustomerStoreActivity.class);
                        intent.putExtra("customer", customer);
                        context.startActivity(intent);
                    }

                } else {
                    Intent intent = new Intent(context, ShopDetailActivity.class);

                    intent.putExtra("customer", customer);
                    context.startActivity(intent);
                }
            }
        });
    }

    private void showText(String str, TextView textView) {
        textView.clearComposingText();
        if (!keyWrold.equals("")) {
            String patten = "" + keyWrold;
            Pattern p = Pattern.compile(patten);
            Matcher m = p.matcher(str);
            SpannableString spannableString = new SpannableString(str);
            while (m.find()) {
                if (str.contains(m.group())) {
                    spannableString.setSpan(
                            new ForegroundColorSpan(0xffec8b44), m.start(),
                            m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            textView.setText(spannableString);
        } else {
            textView.setText(str);
        }
    }

    @Override
    public int getItemCount() {
        return tasklist.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    class ViewHodler extends RecyclerView.ViewHolder {

        TextView tvName;
        TextView tvAddress;
        TextView tvDistance;
        ImageView icon;

        public ViewHodler(View convertView) {
            super(convertView);
            tvName = (TextView) convertView.findViewById(R.id.name);
            tvAddress = (TextView) convertView.findViewById(R.id.address);
            tvDistance = (TextView) convertView.findViewById(R.id.distance);
            icon = (ImageView) convertView.findViewById(R.id.icon);
        }
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        return filter;
    }

    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            tasklist = (List<Customer>) results.values;
            if (results.count > 0) {
                notifyListeners(results.count,tasklist);
            } else {
                notifyListeners(0,null);
            }
            //notifyListeners(results.count, tasklist);
            notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            // TODO Auto-generated method stub
            FilterResults filterResults = new FilterResults();

            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<>(App.mCustomerList);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<Customer> list;
                synchronized (mLock) {
                    list = new ArrayList<>(mOriginalValues);
                }
                filterResults.values = list;
                filterResults.count = list.size();
                keyWrold = "";
            } else {
                String prefixString = prefix.toString().toLowerCase();
                ArrayList<Customer> values;
                synchronized (mLock) {
                    values = new ArrayList<>(mOriginalValues);
                }
                final int count = values.size();
                final ArrayList<Customer> newValues = new ArrayList<>();

                for (int i = 0; i < count; i++) {
                    final Customer value = values.get(i);
                    final String nameText = value.getName().toLowerCase();
                    final String addText = value.getAddress().toLowerCase();
                    // First match against the whole, non-splitted value
                    if (nameText.contains(prefixString) || addText.contains(prefixString)) {
                        newValues.add(value);
                        keyWrold = prefixString;
                    }
                }
                filterResults.values = newValues;
                filterResults.count = newValues.size();
                Log.d("showText", "count:" + count);

            }
            return filterResults;
        }
    };

    private void notifyListeners(int num, List<Customer> tasklist) {
        updateListener.update(num, tasklist);
    }

    public interface UpdateCarListener {
        void update(int num, List<Customer> tasklist);
    }

    public void setUpdateCarListener(UpdateCarListener updateListener) {
        this.updateListener = updateListener;
    }
}